package com.xbongbong.sys.help;

import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.sys.enums.SysEnvEnum;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Component
public class SysEnvHelp {

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CompanyConfigModel companyConfigModel;

    /**
     * 是否灰度
     *
     * @return true:是 fasle:否
     */
    public boolean isGrayEnvironment() {
        return Objects.equals(proBaseConfig.getGray(), BasicConstant.GRAY_FLAG);
    }

    /**
     * 灰度环境添加灰度标识查询条件
     *
     * @param param 查询参数
     */
    public void addGrayEnvironmentQueryCondition(Map<String, Object> param) {
        if (!isGrayEnvironment()) {
            param.put("gray", SysEnvEnum.PROD.getCode());
        }
    }

    public void addGrayEnvironmentQueryCondition4Default(Map<String, Object> param) {
        if (param.containsKey(StringConstant.CORPID) && Objects.equals(param.get(StringConstant.CORPID), StringConstant.ZERO)) {
            if (!isGrayEnvironment()) {
                param.put("gray", SysEnvEnum.PROD.getCode());
            }
        }
    }

    /**
     * Description: 判断公司是否在灰度（redis缓存）
     * @param corpid
     * @return boolean
     * @throws
     * @author 魏荣杰
     * @date 2022/6/16 11:16
     * @since
     */
    public boolean checkIsCrayCompany(String corpid) {
        String key = "ab:policies:0:divdata";
        String value = (String) stringRedisTemplate.opsForHash().get(key, corpid);
        return Objects.equals(value, "serverB");
    }

    /**
     * 判断灰度环境是否启用的开关
     */
    public boolean isGrayEnvironmentEnable() {
        try {
            return companyConfigModel.hasBeenEnable(StringConstant.ZERO, CompanyConfigEnum.GRAY_ENVIRONMENT_ENABLE.getAlias(), EnableEnum.OPEN.getCode().toString());
        } catch (XbbException xbbException) {
            return false;
        }
    }
}
